{% extends 'base.html' %}

{% block title %}编辑碳盘查{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>编辑碳盘查</h1>
        <div>
            <a href="{{ url_for('inventory.inventory_list') }}" class="btn btn-outline-secondary">返回列表</a>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-header">
            <ul class="nav nav-tabs card-header-tabs" id="inventoryTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="basic-info-tab" data-bs-toggle="tab" data-bs-target="#basic-info" type="button" role="tab" aria-controls="basic-info" aria-selected="true">基本信息</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="emission-sources-tab" data-bs-toggle="tab" data-bs-target="#emission-sources" type="button" role="tab" aria-controls="emission-sources" aria-selected="false">关联排放源</button>
                </li>
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content" id="inventoryTabsContent">
                <!-- 基本信息标签页 -->
                <div class="tab-pane fade show active" id="basic-info" role="tabpanel" aria-labelledby="basic-info-tab">
                    <form method="POST" action="{{ url_for('inventory.edit', id=inventory.id) }}">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="name" class="form-label">名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="name" name="name" value="{{ inventory.name }}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="status" class="form-label">状态 <span class="text-danger">*</span></label>
                                <select class="form-select" id="status" name="status" required>
                                    <option value="新建" {% if inventory.status == '新建' %}selected{% endif %}>新建</option>
                                    <option value="执行" {% if inventory.status == '执行' %}selected{% endif %}>执行</option>
                                    <option value="完成" {% if inventory.status == '完成' %}selected{% endif %}>完成</option>
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3 d-none">
                            <div class="col-md-6">
                                <input type="hidden" id="start_time" name="start_time" value="{{ inventory.start_time }}">
                            </div>
                            <div class="col-md-6">
                                <input type="hidden" id="end_time" name="end_time" value="{{ inventory.end_time }}">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="model_categories_id" class="form-label">模型分类 <span class="text-danger">*</span></label>
                                <select class="form-select" id="model_categories_id" name="model_categories_id" required>
                                    <option value="">-- 选择模型分类 --</option>
                                    {% for category in model_categories %}
                                    <option value="{{ category.id }}" {% if inventory.model_categories_id == category.id %}selected{% endif %}>
                                        {{ '　' * (category.level - 1) }}|-- {{ category.name }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label for="category_id" class="form-label">碳盘查目录 <span class="text-danger">*</span></label>
                                <select class="form-select" id="category_id" name="category_id" required>
                                    <option value="">-- 选择盘查目录 --</option>
                                    {% for category in inventory_categories %}
                                    <option value="{{ category.id }}" {% if inventory.category_id == category.id %}selected{% endif %}>
                                        {{ '　' * (category.level - 1) }}|-- {{ category.name }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="organization_boundary" class="form-label">组织边界 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="organization_boundary" name="organization_boundary" value="{{ inventory.organization_boundary }}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="base_year" class="form-label">基准年 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="base_year" name="base_year" value="{{ inventory.base_year }}" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="accounting_standard" class="form-label">核算标准 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="accounting_standard" name="accounting_standard" value="{{ inventory.accounting_standard }}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="accounting_method" class="form-label">核算方式 <span class="text-danger">*</span></label>
                                <select class="form-select" id="accounting_method" name="accounting_method" required>
                                    <option value="建模核算" {% if inventory.accounting_method == '建模核算' %}selected{% endif %}>建模核算</option>
                                    <option value="数据上传" {% if inventory.accounting_method == '数据上传' %}selected{% endif %}>数据上传</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-group row">
                            <div class="col-md-6">
                                <label for="belong_year" class="col-form-label">所属年份</label>
                                <input type="number" class="form-control form-control-sm" id="belong_year" name="belong_year" 
                                       min="2000" max="2100" value="{{ inventory.belong_year }}" required>
                            </div>
                            <div class="col-md-6">
                                <label for="belong_month" class="col-form-label">所属月份</label>
                                <select class="form-control form-control-sm" id="belong_month" name="belong_month" required>
                                    {% for month in range(1,13) %}
                                    <option value="{{ month }}" {% if month == inventory.belong_month %}selected{% endif %}>{{ month }}月</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>


                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="{{ url_for('inventory.inventory_list') }}" class="btn btn-outline-secondary">取消</a>
                            <button type="submit" class="btn btn-primary">更新</button>
                        </div>
                    </form>
                </div>

                <!-- 关联排放源标签页 -->
                <div class="tab-pane fade" id="emission-sources" role="tabpanel" aria-labelledby="emission-sources-tab">
                    <!-- 添加排放源搜索区域 -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <h5 class="card-title">添加排放源</h5>
                            <!-- 添加搜索框 -->
                            <div class="mb-3">
                                <input type="text" id="emissionSourceSearch" class="form-control" placeholder="搜索排放源或因子名称...">
                                <button type="button" class="btn btn-primary mt-2" onclick="searchEmissionSources()">搜索</button>
                            </div>
                            <!-- 搜索结果区域 -->
                            <div id="emissionSourceSearchResults"></div>
                        </div>
                    </div>

                    <!-- 已关联排放源表格 -->
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">已关联排放源</h5>
                            <form id="emissionSourcesForm" method="post" action="{{ url_for('inventory_models.save_emission_sources', inventory_id=inventory.id) }}">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th><input type="checkbox" id="selectAll"></th>
                                            <th>排放源名称</th>
                                            <th>碳排放因子</th>
                                            <th>描述</th>
                                            <th>数据来源</th>
                                            <th>排放源单位</th>
                                            <th>设施</th>
                                            <th>活动数据</th>
                                            <th>值</th>
                                            <th>填报人</th>
                                        </tr>
                                    </thead>
                                    <!-- 在基本信息标签页添加隐藏字段存储当前模型分类ID -->
                                    <input type="hidden" id="currentModelCategoryId" value="{{ inventory.model_categories_id }}">
                                    
                                    <!-- 修改关联排放源表格，显示基于模型分类的排放源 -->
                                    <tbody id="emissionSourcesTableBody">
                                        {% if emission_sources %}
                                            {% for source in emission_sources %}
                                            <tr>
                                                <td><input type="checkbox" name="source_ids" value="{{ source.emission_source_id }}"></td>
                                                <td>{{ source.emission_source }}</td>
                                                <td>
                                                    {% if session.get('role') != 'business_user' %}
                                                        <a href="{{ url_for('inventory_models.edit_factor_by_name', factor_name=source.factor_name) }}" target="_blank">{{ source.factor_name }}</a>
                                                    {% else %}
                                                        <span class="text-muted">{{ source.factor_name }}</span>
                                                    {% endif %}
                                                </td>
                                                <td>{{ source.description }}</td>
                                                <td>{{ source.data_source }}</td>
                                                <td>{{ source.emission_unit }}</td>
                                                <td><input type="text" class="form-control form-control-sm" name="facility_{{ source.emission_source_id }}" value="{{ source.facility|default('None') }}"></td>
                                                <td><input type="number" step="any" class="form-control form-control-sm" name="activity_data_{{ source.emission_source_id }}" value="{{ source.activity_data|default('0') }}"></td>
                                                <td><input type="number" step="any" class="form-control form-control-sm" name="value_{{ source.emission_source_id }}" value="{{ source.value|default('0') }}"></td>
                                                <td><input type="text" class="form-control form-control-sm" name="reporter_{{ source.emission_source_id }}" value="{{ source.reporter|default('None') }}"></td>
                                            </tr>
                                            {% endfor %}
                                        {% elif model_based_sources %}
                                            {% for source in model_based_sources %}
                                            <tr>
                                                <td><input type="checkbox" name="source_ids" value="{{ source.id }}"></td>
                                                <td>{{ source.emission_source }}</td>
                                                <td>{{ source.factor_name|default('-') }}</td>
                                                <td>{{ source.description|default('-') }}</td>
                                                <td>{{ source.data_source|default('-') }}</td>
                                                <td>{{ source.emission_unit|default('-') }}</td>
                                                <td><input type="text" class="form-control form-control-sm" name="facility_{{ source.id }}" value="None"></td>
                                                <td><input type="number" step="any" class="form-control form-control-sm" name="activity_data_{{ source.id }}" value="0"></td>
                                                <td><input type="number" step="any" class="form-control form-control-sm" name="value_{{ source.id }}" value="0"></td>
                                                <td><input type="text" class="form-control form-control-sm" name="reporter_{{ source.id }}" value="None"></td>
                                            </tr>
                                            {% endfor %}
                                        {% else %}
                                            <tr>
                                                <td colspan="11" class="text-center">
                                                    暂无关联排放源
                                                    {% if inventory.model_categories_id %}
                                                    <button type="button" class="btn btn-sm btn-link" onclick="autoAssociateSources()">
                                                        自动关联模型分类下的排放源
                                                    </button>
                                                    {% endif %}
                                                </td>
                                            </tr>
                                        {% endif %}
                                    </tbody>
                                </table>
                                <div class="d-flex justify-content-end mt-3">
                                    <button type="submit" class="btn btn-primary">保存选中排放源</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
// 排放源搜索功能
document.getElementById('searchEmissionSourceBtn').addEventListener('click', searchEmissionSources);
document.getElementById('emissionSourceSearch').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        searchEmissionSources();
    }
});

function searchEmissionSources() {
    const query = document.getElementById('emissionSourceSearch').value.trim();
    fetch(`{{ url_for('inventory_models.search_models') }}?query=${encodeURIComponent(query)}`)
        .then(response => response.json())
        .then(data => {
            let html = '<div class="row g-3">';
            data.forEach(source => {
                html += `
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-body p-2">
                            <h6 class="card-title mb-1">${source.emission_source}</h6>
                            <p class="card-text small mb-1">
                                <span class="text-muted">描述:</span> ${source.description || '-'}
                            </p>
                            <p class="card-text small mb-2">
                                <span class="text-muted">单位:</span> ${source.emission_unit || '-'}
                            </p>
                            <button class="btn btn-sm btn-primary w-100" 
                                onclick="addEmissionSource('${source.id}')">
                                添加
                            </button>
                        </div>
                    </div>
                </div>`;
            });
            html += '</div>';
            document.getElementById('emissionSourceSearchResults').innerHTML = html;
        });
}

function addEmissionSource(sourceId) {
    fetch(`{{ url_for('inventory_models.add_emission_source', inventory_id=inventory.id) }}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `model_id=${sourceId}`
    })
    .then(response => {
        if (response.ok) {
            return response.text();
        }
        throw new Error('添加失败');
    })
    .then(message => {
        alert(message);
        
        // 手动切换到关联排放源标签页
        const emissionTab = document.getElementById('emission-sources-tab');
        const tab = new bootstrap.Tab(emissionTab);
        tab.show();
        
        // 从隐藏字段获取inventory_id
        const inventoryId = document.getElementById('currentModelCategoryId').value;
        
        // 使用正确的端点名称刷新已关联排放源表格
        fetch(`{{ url_for('inventory_models.search_models') }}?inventory_id=${inventoryId}`)
            .then(response => response.json())
            .then(data => {
                updateEmissionSourcesTable(data);
            });
    })
    .catch(error => {
        alert(error.message);
    });
}
</script>
<script>
    document.getElementById('selectAll').addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('input[name="source_ids"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // 页面加载时自动全选
    document.addEventListener('DOMContentLoaded', function() {
        const selectAllCheckbox = document.getElementById('selectAll');
        selectAllCheckbox.checked = true;
        
        // 触发change事件以选中所有子复选框
        const event = new Event('change');
        selectAllCheckbox.dispatchEvent(event);
    });
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 全选功能
    const selectAllCheckbox = document.getElementById('selectAll');
    selectAllCheckbox.checked = true;
    selectAllCheckbox.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('input[name="source_ids"]');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });

    // 动态计算功能
    const activityInputs = document.querySelectorAll('input[name^="activity_data"]');
    activityInputs.forEach(input => {
        input.addEventListener('input', async function() {
            const activityData = parseFloat(this.value);
            if (!isNaN(activityData)) {
                const row = this.closest('tr');
                const factorName = row.querySelector('td:nth-child(3)').textContent.trim();
                
                try {
                    // 调用API获取碳排值
                    const response = await fetch(`/inventory/models/get_emission_value/${encodeURIComponent(factorName)}`);
                    const data = await response.json();
                    
                    if (data.emission_value !== undefined) {
                        // 计算并更新值字段
                        const calculatedValue = activityData * data.emission_value;
                        const valueInput = row.querySelector('input[name^="value"]');
                        valueInput.value = calculatedValue.toFixed(2);
                    }
                } catch (error) {
                    console.error('获取碳排值失败:', error);
                }
            }
        });
    });
});
</script>
{% endblock %}



